#ifndef STRING_H
#define STRING_H
#include <cstring>
/*
	overloaded operator:
	operators of assigment("="),subscript("[]"),call("()"),member access arrow("->")
are required by language to be defined as class member operators.
	the following four operators cannot be overloaded:  ::  .*  .  ?:
*/

class String{
public:
	//overloaded set of constructors
	String(const char *);
	String(const String &);

	~String(){delete[] _string;};
	/*overloaded set of assigment operators
		return value of each assigment operator is a reference to object of type String 
	 in order to support chain assigment.
	*/
	String& operator=(const char *);
	String& operator=(const String &);
	/*overloaded subscript operator
		the return value of subscript operator is a lvalue so that it can appear in the left size of an expression,
	for example: String s("12345"); s[0]='5';
	*/
	char& operator[](int) const;
	//overloaded set of equality operators
	bool operator==(const char *s) const;
friend	bool operator==(const String &,const String &);
	//member access functions
	int size() const{return _size;}
	char* c_str() const{return _string;}
	//overloaded set of += operators
	String& operator+=(const char *);
	String& operator+=(const String &);

private:
	int _size;
	char *_string;
};

inline String& String::operator+=(const char *s){
	if(s){//test whether s is null
		String tmp(*this); //back up this object for later use in strcpy()
		_size+=strlen(s);  //update _size of this object
		delete[] _string;  //free original heap memory pointed by _string
		_string=new char[_size+1];  //allocate new heap memory(1 represents the null terminator) and initialize _string with its address;
		strcpy(_string,tmp._string);//copy original chars to new allocated memory
		strcpy(_string+tmp._size,s);//copy chars pointed by s to new allocated memory following the original chars.
	}
	return *this;
}
inline String& String::operator+=(const String &s){
	if(s._string){
		String tmp(*this);
		_size+=s._size;
		delete[] _string;
		_string=new char[_size+1];
		strcpy(_string,tmp._string);
		strcpy(_string+tmp._size,s._string);
	}
	return *this;
}

#endif